package tbs.framework.async.task.container

import tbs.framework.async.container.IAsyncTaskContainer
import tbs.framework.async.container.IAsyncTaskBroker
import tbs.framework.async.container.IAsyncTaskService
import java.time.Duration
import java.util.concurrent.atomic.AtomicBoolean

abstract class AbstractAsyncTaskService(
    private val container: IAsyncTaskContainer,
    private val asyncTaskExecutor: IAsyncTaskBroker,
    var blockTime: Duration = Duration.ofSeconds(15)
) : IAsyncTaskService {


    val thread: Thread = Thread(Runnable {
        val asyncTaskExecutor = this.asyncTaskExecutor;
        while (isService()) {
            Thread.currentThread().join(blockTime.toMillis());
            for (task in container.tasks()) {
                asyncTaskExecutor.execute(task, this)
            }
        }
    }, "AsyncTaskService")

    override fun getAsyncTaskBroker(): IAsyncTaskBroker {
        return asyncTaskExecutor
    }

    override fun container(): IAsyncTaskContainer {
        return container
    }

    private val isService: AtomicBoolean = AtomicBoolean(false);
    override fun service() {
        if (isService.compareAndSet(false, true)) {
            thread.start()
        }
    }

    /**
     * 异步任务服务停止
     *
     */

    abstract fun serviceStop();


    override fun stop() {
        serviceStop()
        isService.set(false)
    }

    override fun isService(): Boolean {
        return isService.get()
    }
}